package 力扣;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author yyq
 * @create 2022-04-06 14:21
 *  中序遍历:
 *  递归法
 *  迭代法
 */
public class leetcode94 {
    public List<Integer> inorderTraversal(TreeNode root) {

        List<Integer> list=new ArrayList<>();
        if(root == null) return list;
        inorder(list,root);
        return list;
    }

    private void inorder(List<Integer> list, TreeNode root) {
        if(root.left!=null) inorder(list,root.left);
        if(root==null) return;
        else list.add(root.val);
        if(root.right!=null) inorder(list,root.right);
    }

    public List<Integer> inorderIterative(TreeNode root) {

        List<Integer> list=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        if(root == null) return list;
        TreeNode temp=root;
        stack.push(root);
        while (!stack.isEmpty()){
            if(temp.left!=null){
                stack.push(temp.left);
                temp=temp.left;
            }else {
                TreeNode pop = stack.pop();
                list.add(pop.val);
                if(pop.right!=null){
                    temp= pop.right;
                    stack.push(pop.right);
                }
            }
        }
        return list;
    }
}
